package com.example.easytts.controller

import com.example.easytts.model.Language
import com.example.easytts.repository.LanguageRepository
import com.example.easytts.repository.VoiceRepository
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/api/admin/language")
class LanguageController(private val repo: LanguageRepository, private val voiceRepo: VoiceRepository) {
    @GetMapping(produces = [MediaType.APPLICATION_JSON_VALUE])
    fun list(): ResponseEntity<List<Language>> {
        return ResponseEntity.ok()
            .header("Cache-Control", "no-cache, no-store, must-revalidate")
            .header("Pragma", "no-cache")
            .header("Expires", "0")
            .header("Last-Modified", System.currentTimeMillis().toString())
            .contentType(MediaType.APPLICATION_JSON)
            .body(repo.findAll())
    }
    
    @GetMapping("/list-custom", produces = [MediaType.APPLICATION_JSON_VALUE])
    fun listCustom(): ResponseEntity<Map<String, Any>> {
        val languages = repo.findAll()
        val response = mapOf(
            "code" to 200,
            "message" to "success",
            "data" to languages,
            "total" to languages.size
        )
        return ResponseEntity.ok()
            .contentType(MediaType.APPLICATION_JSON)
            .body(response)
    }
    
    @PostMapping(produces = [MediaType.APPLICATION_JSON_VALUE])
    fun add(@RequestBody l: Language): ResponseEntity<Any> {
        val exists = repo.findAll().any { it.name == l.name }
        if (exists) {
            return ResponseEntity.badRequest()
                .contentType(MediaType.APPLICATION_JSON)
                .body(mapOf(
                    "code" to 400,
                    "message" to "语言名称已存在"
                ))
        }
        return try {
            val savedLanguage = repo.save(l)
            ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(mapOf(
                    "code" to 200,
                    "message" to "添加成功",
                    "data" to savedLanguage
                ))
        } catch (e: Exception) {
            ResponseEntity.badRequest()
                .contentType(MediaType.APPLICATION_JSON)
                .body(mapOf(
                    "code" to 400,
                    "message" to "添加失败: ${e.message}"
                ))
        }
    }
    @DeleteMapping("/{id}")
    fun del(@PathVariable id: Long): ResponseEntity<Any> {
        return try {
            val existingLanguage = repo.findById(id).orElse(null)
            if (existingLanguage == null) {
                return ResponseEntity.status(404)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(mapOf(
                        "code" to 404,
                        "message" to "语言不存在"
                    ))
            }
            // 先删除所有关联的Voice
            val voices = voiceRepo.findByLanguageId(existingLanguage.uuid)
            voiceRepo.deleteAll(voices)
            // 再删除Language
            repo.deleteById(id)
            ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(mapOf(
                    "code" to 200,
                    "message" to "删除成功"
                ))
        } catch (e: Exception) {
            ResponseEntity.badRequest()
                .contentType(MediaType.APPLICATION_JSON)
                .body(mapOf(
                    "code" to 400,
                    "message" to "删除失败: ${e.message}"
                ))
        }
    }
    
    @PutMapping("/{id}")
    fun update(@PathVariable id: Long, @RequestBody language: Language): ResponseEntity<Any> {
        val exists = repo.findAll().any { it.name == language.name && it.id != id }
        if (exists) {
            return ResponseEntity.badRequest()
                .contentType(MediaType.APPLICATION_JSON)
                .body(mapOf(
                    "code" to 400,
                    "message" to "语言名称已存在"
                ))
        }
        return try {
            val existingLanguage = repo.findById(id).orElse(null)
            if (existingLanguage == null) {
                return ResponseEntity.status(404)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(mapOf(
                        "code" to 404,
                        "message" to "语言不存在"
                    ))
            }
            
            val updatedLanguage = existingLanguage.copy(
                name = language.name,
                uuid = language.uuid,
                locale = language.locale
            )
            val savedLanguage = repo.save(updatedLanguage)
            
            // 同步更新Voice表中languageName字段
            val voices = voiceRepo.findByLanguageId(existingLanguage.uuid)
            val updatedVoices = voices.map { it.copy(languageName = language.name) }
            voiceRepo.saveAll(updatedVoices)
            
            ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(mapOf(
                    "code" to 200,
                    "message" to "更新成功",
                    "data" to savedLanguage
                ))
        } catch (e: Exception) {
            ResponseEntity.badRequest()
                .contentType(MediaType.APPLICATION_JSON)
                .body(mapOf(
                    "code" to 400,
                    "message" to "更新失败: ${e.message}"
                ))
        }
    }
    
    @GetMapping("/{id}")
    fun getById(@PathVariable id: Long): ResponseEntity<Any> {
        return try {
            val language = repo.findById(id).orElse(null)
            if (language == null) {
                ResponseEntity.status(404)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(mapOf(
                        "code" to 404,
                        "message" to "语言不存在"
                    ))
            } else {
                ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(mapOf(
                        "code" to 200,
                        "message" to "success",
                        "data" to language
                    ))
            }
        } catch (e: Exception) {
            ResponseEntity.badRequest()
                .contentType(MediaType.APPLICATION_JSON)
                .body(mapOf(
                    "code" to 400,
                    "message" to "获取失败: ${e.message}"
                ))
        }
    }
} 